import Vue from 'vue'
import VueRouter from 'vue-router'
import {
    getUserListApi
} from '@/api/user'
// 登录组件
import Login from '@/views/login'

// 后台首页
import Index from '@/views/index'
// 欢迎页面
import Welcome from '@/views/index/welcome'
// 用户组件
import User from '@/views/user'
// 角色组件
import Role from '@/views/role'
// 权限组件
import Privilege from '@/views/privilege'
// 分类组件
import Cate from '@/views/cate'
// 参数组件
import Params from '@/views/params/index.vue'
// 商品组件
import Goods from '@/views/goods/index.vue'
import GoodsAdd from '@/views/goods/components/goods-add.vue'
import GoodsEdit from '@/views/goods/components/goods-edit.vue'
// 订单组件
import Orders from '@/views/orders/index.vue'
// 报表组件
import Report from '@/views/report/index.vue'

// 404 页面
import NotFound from '@/views/NotFound'

Vue.use(VueRouter)

const routes = [{
        path: '/login',
        component: Login
    }, {
        path: '/',
        component: Index,
        redirect: '/welcome',
        // 二级路由的path的设定是根据权限中path字段来定义的
        children: [{
                path: '/welcome',
                component: Welcome
            }, {
                path: '/users',
                component: User
            }, {
                path: '/roles',
                component: Role
            },
            {
                path: '/rights',
                component: Privilege
            },
            {
                path: '/categories',
                component: Cate
            },
            {
                path: '/params',
                component: Params
            },
            {
                path: '/goods',
                component: Goods
            },
            {
                path: '/goodsAdd',
                component: GoodsAdd
            },
            {
                path: '/goodsEdit/:id',
                component: GoodsEdit
            },
            {
                path: '/orders',
                component: Orders
            },
            {
                path: '/reports',
                component: Report
            }
        ]
    },
    // 404页面
    {
        path: '*',
        component: NotFound,
        name: '404'
    }
]

const router = new VueRouter({
    routes
})

// 全局路由导航守卫
router.beforeEach(async(to, from, next) => {
    // 其中login路由和404路由是不需要做登录校验了，直接放行
    if (to.path === '/login' || to.name === '404') {
        return next()
    }
    // 其他路由都需要做登录校验
    const token = window.sessionStorage.getItem('token')
    if (!token) {
        Vue.prototype.$message.error('请先登录')
        return next('/login')
    }
    // token是否有效
    const res = await getUserListApi({})
    if (res.meta.status === 400 && res.meta.msg === '无效token') {
        Vue.prototype.$message.error('请先登录')

        // 删除token
        window.sessionStorage.clear()
        return next('/login')
    }

    // 有token且是有效的，直接放行
    next()
})

export default router